package alarm.ruiqi.com.alarm_pro.options.alarm;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.ImageButton;

import com.ab.util.AbWifiUtil;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;

import alarm.ruiqi.com.alarm_pro.R;
import alarm.ruiqi.com.alarm_pro.domain.AlarmEntity;
import alarm.ruiqi.com.alarm_pro.options.webview.GeneralWebviewFragment;
import alarm.ruiqi.com.alarm_pro.service.AlarmServiceImpl;
import alarm.ruiqi.com.alarm_pro.service.MobileApplication;
import alarm.ruiqi.com.alarm_pro.utils.Constant;

public class AlarmedActivity extends FragmentActivity {

    private  MediaPlayer player;
    private AlarmEntity entity;
    private  Long timeNow;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarmed);

        timeNow  = System.currentTimeMillis();
        entity = (AlarmEntity) getIntent().getSerializableExtra(Constant.GENERAL_SAVE_KEY);
        LogUtils.i("entity = "+entity);
      //  TextView textView = (TextView) findViewById(R.id.alarmed_playing_show);
     //   textView.setText("正在响铃:"+entity.getAlarmUriTitle());


        if (AbWifiUtil.isConnectivity(this) ||AbWifiUtil.isConnectivity(this)){
            GeneralWebviewFragment webview = GeneralWebviewFragment.newInstance(getString(R.string.alarmrd_url));
            getSupportFragmentManager().beginTransaction().replace(R.id.alarmed_content,webview).commit();
        }
        else {
            final ImageButton imageButton = (ImageButton) findViewById(R.id.alarmed_pause);
            imageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (player.isPlaying()) {
                        player.pause();
                        imageButton.setImageResource(R.mipmap.videoplayer_icon_play_highlighted);
                    } else {
                        player.start();
                        imageButton.setImageResource(R.mipmap.videoplayer_icon_stop_highlighted);
                    }
                }
            });
            findViewById(R.id.alarmed_content).setVisibility(View.GONE);
            try {
                change2Play();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }




    }

    private void change2Play() throws Exception {
        // if(entity !=null && !TextUtils.isEmpty(entity.getAlarmUri())){
      player = MediaPlayer.create(this, R.raw.default_alarm);
        if (player == null) {
            AssetFileDescriptor fileDesc = getResources().openRawResourceFd(R.raw.default_alarm);
            if (fileDesc != null) {
                player = new MediaPlayer();
                player.setDataSource(fileDesc.getFileDescriptor(), fileDesc.getStartOffset(), fileDesc.getLength());
                fileDesc.close();
                if (player == null) return;
            }
        }
        // MediaPlayer.create();
        final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) == 0) {
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM) / 2, 0);
        }

//      player.setAudioStreamType(AudioManager.STREAM_ALARM);
        player.setLooping(true);
        try {
            player.prepare();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        LogUtils.i("开始播放");
        player.start();

//        }
    }


    @Override
    public void finish() {
        //设置下一个闹钟
        AlarmServiceImpl service = new AlarmServiceImpl(this);
        service.checkNextAlarm(entity, timeNow);
        LogUtils.i("entity =" + entity);
        try {
            MobileApplication.getInstance().getDefaultDbutils().update(entity);
            LogUtils.i(" 保存闹钟成功! ");
        } catch (DbException e) {
            e.printStackTrace();
            LogUtils.i(" 保存闹钟失败! ");
            return;
        }
        service.createAlarm(this, entity, entity.isEnable());
        if (player != null) {
            player.release();
            player = null;
        }
        super.finish();
    }
}
